package com.foxchen.ddns.service.impl;

import com.foxchen.ddns.config.DDNSConfig;
import com.foxchen.ddns.service.IpGetServiceV4;
import com.foxchen.ddns.service.IpGetServiceV6;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Service
public class IpGetServiceImpl implements IpGetService{
    @Resource
    private Map<String, IpGetServiceV4> ipV4GetMap;
    @Resource
    private Map<String, IpGetServiceV6> ipV6GetMap;
    @Resource
    private DDNSConfig ddnsConfig;

    @Override
    public String getLocalPublicIp(DDNSConfig.Detail detail){
        return getLocalPublicIp(detail.getType());
    }

    @Override
    public String getLocalPublicIp(String type){
        log.info("begin getLocalPublicIp,type={}",type);
        if("v4".equals(type)){
            for (String url : ddnsConfig.getV4()) {
                IpGetServiceV4 ipGetServiceV4 = ipV4GetMap.get(url);
                if(null == ipGetServiceV4){
                    log.error("{} is not support get ipv4.",url);
                    continue;
                }
                String ip = ipGetServiceV4.getIp(url);
                if (StringUtils.isNotBlank(ip)) {
                    return ip;
                }
            }

            throw new RuntimeException("get ip v4 error.all url is not get.");
        } else if ("v6".equals(type)){
            for (String url : ddnsConfig.getV6()) {
                IpGetServiceV6 ipGetServiceV6 = ipV6GetMap.get(url);
                if(null == ipGetServiceV6){
                    log.error("config:{} => is not support get ipv6.",url);
                    continue;
                }

                String ip = ipGetServiceV6.getIp(url);
                log.info("url:{}====>ip result:{}",url,ip);
                if (StringUtils.isNotBlank(ip)) {
                    return ip;
                }
            }
            throw new RuntimeException("get ip v6 error.all url is not get.");
        }

        throw new RuntimeException("type:" + type +" is not support.");
    }
}
